package com.csweimei.rentmanagementtreasure.tenant.viewModel;

import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;

import androidx.databinding.ObservableField;

import com.csweimei.rentmanagementtreasure.R;
import com.csweimei.rentmanagementtreasure.SplashActivity;
import com.csweimei.rentmanagementtreasure.http.ApiService;
import com.csweimei.rentmanagementtreasure.http.Repository;
import com.csweimei.rentmanagementtreasure.http.entity.BaseResult;
import com.csweimei.rentmanagementtreasure.http.entity.LoginBean;
import com.csweimei.rentmanagementtreasure.tenant.ui.act.mine.AboutActivity;
import com.csweimei.rentmanagementtreasure.utils.CacheUtils;
import com.csweimei.rentmanagementtreasure.utils.DialogUtils;
import com.csweimei.rentmanagementtreasure.utils.UserUtils;
import com.csweimei.rentmanagementtreasure.viewModel.TitleVM;
import com.csweimei.rentmanagementtreasure.pop.WarnPop;
import com.gtdev5.geetolsdk.mylibrary.beans.LoginInfoBean;
import com.gtdev5.geetolsdk.mylibrary.beans.ResultBean;
import com.gtdev5.geetolsdk.mylibrary.beans.UpdateBean;
import com.gtdev5.geetolsdk.mylibrary.callback.BaseCallback;
import com.gtdev5.geetolsdk.mylibrary.contants.Contants;
import com.gtdev5.geetolsdk.mylibrary.http.Base64HttpUtils;
import com.gtdev5.geetolsdk.mylibrary.http.HttpUtils;
import com.gtdev5.geetolsdk.mylibrary.util.DataSaveUtils;
import com.gtdev5.geetolsdk.mylibrary.util.DeviceUtils;
import com.gtdev5.geetolsdk.mylibrary.util.MapUtils;
import com.gtdev5.geetolsdk.mylibrary.util.SpUtils;
import com.gtdev5.geetolsdk.mylibrary.util.Utils;
import com.gtdev5.geetolsdk.mylibrary.widget.CenterDialog;
import com.lxj.xpopup.XPopup;

import java.util.HashMap;
import java.util.Map;

import io.reactivex.observers.DisposableObserver;
import me.goldze.mvvmhabit.binding.command.BindingAction;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.utils.RxUtils;
import me.goldze.mvvmhabit.utils.SPUtils;
import me.goldze.mvvmhabit.utils.ToastUtils;
import okhttp3.Request;
import okhttp3.Response;

public class SetVM extends TitleVM {


    public ObservableField<String> cache = new ObservableField<>("0B");

    public BindingCommand clear = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            new CacheUtils().clearCache(mActivity);
        }
    });

    public BindingCommand about = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            startActivity(AboutActivity.class);
        }
    });

    public BindingCommand zx = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            if (model.isLogin()){
                new XPopup.Builder(mActivity)
                        .enableDrag(true)
                        .asCustom(new WarnPop(mActivity, "注销账号",
                                "1．账号注销后应用内所有个人数据将会被清空。 \t2．账号无法登录，且购买的会员权益也无法继续使用与恢复。 \t3．如因注销账号所造成的损失，我们不承担任何责任。 \t4．注销手机号可重新注册，生成的账号为全新的账号，不包含注销前任何消息，请谨慎操作！", (s) ->
                                logOut()
                        )).show();
            }else {
                ToastUtils.showShort("您还未登录，无法进行注销账号操作");
            }

        }
    });

    public BindingCommand out = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            new XPopup.Builder(mActivity)
                    .enableDrag(true)
                    .asCustom(new WarnPop(mActivity, "退出登录", "确定退出当前账号？", (s) -> {
                        UserUtils.clear();
//                        Utils.setLoginInfo("", "", "");
                        model.setLogin(new LoginBean());
                        ToastUtils.showShort("退出登录成功");
                    }
                    )).show();


        }
    });

    private void logOut() {
        Map<String, String> map = new HashMap<>();
        map.put("userid", model.getLoginInfo().getData().getUser_id());
        model.logoff(map)
                .compose(RxUtils.schedulersTransformer())
                .compose(RxUtils.exceptionTransformer())
                .doOnSubscribe(this)
                .doOnSubscribe(disposable -> {
                })
                .subscribe(new DisposableObserver<BaseResult>() {
                    @Override
                    public void onNext(BaseResult bean) {
                        if (bean.issucc) {
                            zxOk();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void zxOk() {
        UserUtils.clear();
        SpUtils.getInstance().clear();
//        Utils.setLoginInfo("", "", "");
        model.setLogin(new LoginBean());
        ToastUtils.showShort("注销成功");

        bindDevice();

    }


    public SetVM(Application mApplication, Repository mRepository) {
        super(mApplication, mRepository);
        setTitleText("设置");
        cache.set(new CacheUtils().humanReadableByteCount(mActivity,true));
    }




    private boolean isFirstRegister; // 是否首次注册
    /***
     * 绑定device数据
     */
    public void bindDevice() {
        isFirstRegister = SpUtils.getInstance().getBoolean(Contants.FIRST_REGISTER, true);

        if (TextUtils.isEmpty(DeviceUtils.getSpDeviceId()) && TextUtils.isEmpty(DeviceUtils.readDeviceID(mActivity))) {
            // app和sd卡都没有，都存一份
            String imei = DeviceUtils.getUUID();
            DeviceUtils.saveDeviceID(imei, mActivity);
            DeviceUtils.putSpDeviceId(imei);
        } else if (TextUtils.isEmpty(DeviceUtils.getSpDeviceId()) && !TextUtils.isEmpty(DeviceUtils.readDeviceID(mActivity))) {
            // sd卡有，app没有，则存一份到app
            DeviceUtils.putSpDeviceId(DeviceUtils.readDeviceID(mActivity));
        } else {
            // app有，sd卡没有，则存一份到sd卡
            DeviceUtils.saveDeviceID(DeviceUtils.getSpDeviceId(), mActivity);
        }
        registerId();
    }

    /**
     * 注册设备id
     */
    private void registerId() {
        if (isFirstRegister) {
            if (Utils.isNetworkAvailable(mActivity)) {
                Base64HttpUtils.getInstance().postRegister(new BaseCallback<ResultBean>() {
                    @Override
                    public void onRequestBefore() {
                    }
                    @Override
                    public void onFailure(Request request, Exception e) {
                    }

                    @Override
                    public void onSuccess(Response response, ResultBean o) {
                        if (o != null) {
                            if (o.isIssucc()) {
                                // 注册成功，调取App数据接口
                                SpUtils.getInstance().putBoolean(Contants.FIRST_REGISTER, false);
                            } else {
                                // 注册失败，弹出提示
                                if (!TextUtils.isEmpty(o.getMsg())) {
                                    com.gtdev5.geetolsdk.mylibrary.util.ToastUtils.showShortToast(o.getMsg());
                                }
                            }
                        }
                    }

                    @Override
                    public void onError(Response response, int errorCode, Exception e) {
                    }
                });
            }
        }
    }




}
